// API配置
const API_BASE = window.location.origin;

// DOM元素
const form = document.getElementById('qrForm');
const urlInput = document.getElementById('urlInput');
const mhidInput = document.getElementById('mhidInput');
const loading = document.getElementById('loading');
const result = document.getElementById('result');
const error = document.getElementById('error');
const qrImage = document.getElementById('qrImage');
const downloadBtn = document.getElementById('downloadBtn');
const errorMessage = document.getElementById('errorMessage');

// 表单提交处理
form.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const url = urlInput.value.trim();
    const mhid = mhidInput.value.trim() || 'sELAVNMfK8k';
    
    if (!url) {
        showError('请输入网址或文本内容');
        return;
    }
    
    // 显示加载状态
    showLoading();
    
    try {
        const response = await fetch(`${API_BASE}/qr?url=${encodeURIComponent(url)}&mhid=${encodeURIComponent(mhid)}`);
        const data = await response.json();
        
        if (data.success) {
            showResult(data.url);
        } else {
            showError(data.error || '生成二维码失败');
        }
    } catch (err) {
        console.error('Error:', err);
        showError('网络错误，请稍后重试');
    }
});

// 显示加载状态
function showLoading() {
    loading.classList.remove('hidden');
    result.classList.add('hidden');
    error.classList.add('hidden');
}

// 显示结果
function showResult(imageUrl) {
    loading.classList.add('hidden');
    result.classList.remove('hidden');
    qrImage.src = imageUrl;
    
    // 设置下载链接
    downloadBtn.onclick = () => {
        const link = document.createElement('a');
        link.href = imageUrl;
        link.download = `qrcode-${Date.now()}.png`;
        link.target = '_blank';
        link.click();
    };
}

// 显示错误
function showError(message) {
    loading.classList.add('hidden');
    error.classList.remove('hidden');
    errorMessage.textContent = message;
}

// 输入框回车快捷提交
urlInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        form.dispatchEvent(new Event('submit'));
    }
});

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', () => {
    // 自动聚焦到输入框
    urlInput.focus();
    
    // 添加一些示例数据
    urlInput.placeholder = '例如：https://github.com 或 你好世界';
});
